package monitoring.sla.latency;

import java.util.HashMap;

import monitoring.utility.StaticFields;

import store.hibernate.Event;

public class LatencyManager {

	private Latency latency;
	private HashMap<String, Event> eventMap;

	public LatencyManager(Latency latency) {
		this.latency=latency;
		eventMap=new HashMap<String, Event>();
	}
	
	 public void makeTrans(Event event) {
		 if(	(latency.getOperationName().size()>0) && 
				 !(latency.getOperationName().contains(event.getWsOperation().getName()))
			)
			 return;
		 //calcolo la chiave composta da Nome Operazione, Sessione e numero di sequenza
		 String key=event.getWsOperation().getName()+event.getSession()+event.getSeqNumber();
		 boolean containsKey=eventMap.containsKey(key);
		 if(event.getDirection()==StaticFields.INB_CHAR){
			if(!(containsKey))
				eventMap.put(key, event);
			else
				System.err.println("chiamo la stessa operazione con lo stesso numero di sequenza");
		 }
		 else{
			 if(containsKey){
				 Event eventRequest = eventMap.get(key);
				 long responseTime=event.getTimestamp()-eventRequest.getTimestamp();
				 if (responseTime>latency.getMaxDuration()) {
 					System.out.println("LATENCY VIOLATION DETECTED. This is the trace of the violation:");
 					System.out.println("T request = "+eventRequest.getTimestamp());
 					System.out.println("T response = "+event.getTimestamp());
 					System.out.println("diff= "+responseTime);
 				}
					eventMap.remove(key);
			 }
		 }
	 }
	 

}
